from django.shortcuts import render
from django_redis import get_redis_connection
from drf_haystack.viewsets import HaystackViewSet
from rest_framework.filters import OrderingFilter
from rest_framework.generics import ListAPIView, CreateAPIView

from goods.models import GoodsCategory, SKU
from rest_framework.views import APIView
from rest_framework.response import Response

from goods.serializers import GoodsSerializers, SKUIndexSerializer, UserGoodsHistorySerializer

from goods.utils import GoodsPage


# Create your views here.

# 商品分类视图  eg: 手机 > 手机通讯 > 手机
class GoodCategorieView(APIView):
    def get(self, request, pk):
        # 获取三级分类对象
        cat3 = GoodsCategory.objects.get(id=pk)
        # 获取二级分类对象和一级分类对象
        cat2 = cat3.parent
        cat1 = cat2.parent

        return Response({
            'cat1': cat1.name,
            'cat2': cat2.name,
            'cat3': cat3.name,

        })


# 物品视力   SKU
class GoodsView(ListAPIView):
    """
        商品列表页数据获取
    """
    # queryset = SKU.objects.filter(category_id=)
    serializer_class = GoodsSerializers

    #  设置分页
    pagination_class = GoodsPage
    # 排序
    filter_backends = [OrderingFilter]
    ordering_fields = ['create_time', 'price', 'sales']

    def get_queryset(self):
        pk = self.kwargs['pk']

        return SKU.objects.filter(category_id=pk)


# SKU索引实图的实现
class SKUIndexView(HaystackViewSet):
    pagination_class = GoodsPage

    # 指定模型类对象
    index_models = [SKU]

    serializer_class = SKUIndexSerializer


# 用户中心里的浏览历史视图
class UserGoodsHistoryView(CreateAPIView, ListAPIView):
    """
        保存和获取用户浏览的商品信息
    """

    # serializer_class = UserGoodsHistorySerializer
    # serializer_class =

    # queryset = SKU.objects.filter(id__in=)

    def get_serializer_class(self):
        # 根据不同的请求方式，返回不同的序列化器
        if self.request.method == "POST":
            return UserGoodsHistorySerializer
        else:
            return GoodsSerializers

    def get_queryset(self):
        # 连接redis缓存
        conn = get_redis_connection('history')
        user = self.request.user
        # 获取列表数据
        sku_ids = conn.lrange('history_%s' % user.id, 0, 5)
        return SKU.objects.filter(id__in=sku_ids)
